﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BAL;
using Entity;
using Common;
using System.Web.Mail;
namespace Web
{
    public partial class FindPassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string email =this.txtEmail.Text.Trim();//文本框中填写Email
            if (string.IsNullOrEmpty(email) || email == "")
            {
                Response.Write("<script>alert('Email不能为空');</script>");
                return;
            }
            else 
            {
                if (Users.CheckUserExistByEmail(email))
                {
                    UserInfo user=Users.GetUserInfoByEmail(email);
                    string password =Str(6);
                    if (password!=null)
                    {
                        user.PassWord = Utility.MD5(Str(6));
                        Users.Edit(user);
                        string result=sendMail(txtEmail.Text, "海淀教学平台用户", "找回密码", "<p>用户您好：</p>\t恭喜您成功的获取密码,您的新密码为："+password+"<p>请您及时修改您的密码！！</p>");
                        if (string.IsNullOrEmpty(result))
                        {

                            //Response.Write("<script>alert('用户你好，您的密码已经发送到您的邮箱中，请您及时查收。');window.close();</script>");
                            Utility.ShowJsAlertAndCloseRefresh("用户你好，您的密码已经发送到您的邮箱中，请您及时查收。",this);
                        }
                        else 
                        {
                            Response.Write("<script>alert('系统出现故障，请您稍后重试');</script>");     
                        }
                    }
                    
                    //userInfo.PinYin = Module_String.GetPYString(Name.Text.Trim());
                    //userInfo.PassWord = Utility.MD5(PassWord.Text.Trim());
                }
                else
                {
                    Response.Write("<script>alert('不好意思，你输入的邮箱无法使用');</script>");
                }
            }
        }
        /// <summary>
        /// 生成随机字母与数字
        /// </summary>
        /// <param name="IntStr">生成长度</param>
        /// <returns></returns>
        public static string Str(int Length)
        {
            return Str(Length, false);
        }
        /// <summary>
        /// 生成随机字母与数字
        /// </summary>
        /// <param name="Length">生成长度</param>
        /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
        /// <returns></returns>
        public static string Str(int Length, bool Sleep)
        {
            if (Sleep)
                System.Threading.Thread.Sleep(3);
            char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
            string result = "";
            int n = Pattern.Length;
            System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
            for (int i = 0; i < Length; i++)
            {
                int rnd = random.Next(0, n);
                result += Pattern[rnd];
            }
            return result;
        }
        /// <summary>
        /// 发送默认电子邮件
        /// </summary>
        /// <param name="Recipient">设定收件人地址</param>
        /// <param name="RecipientName">收件人姓名</param>
        /// <param name="Subject">设定邮件主题</param>
        /// <param name="Body">设定邮件正文</param>
        /// <returns></returns>
        public string sendMail(string Recipient, string RecipientName, string Subject, string Body)
        {
            /*
             * *@sohu.com;*@263.net;*@tom.com;*@sina.com;*@126.com;*@21cn.com
             * */
            SmtpMail ESM = new SmtpMail();

            ESM.RecipientName = RecipientName;//设定收件人姓名
            ESM.RecipientMaxNum = 5;


            ESM.AddRecipient(Recipient);//设定收件人地址（必须填写）。
            //ESM.AddRecipient("lion-a@sohu.com","lionsky.net@tom.com");也可以直接传入一个字符串数组，设定一组收件人。


            //System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString
            String ReplyEMail = System.Configuration.ConfigurationManager.AppSettings["ReplyEMail"];//获取发件人地址
            String ReplyEMailPassword = System.Configuration.ConfigurationManager.AppSettings["ReplyEMailPassword"];//获取发件人邮箱的密码
            String ReplyEMailDomain = System.Configuration.ConfigurationManager.AppSettings["ReplyEMailDomain"];//获取发件人邮箱验证
            ESM.From = ReplyEMail;//设定发件人地址(必须填写)
            ESM.FromName = RecipientName;//设定发件人姓名
            //ESM.AddAttachment("D:\\Project\\ASP.NET\\Exam\\Exam_C\\ReadMe.txt","D:\\Project\\ASP.NET\\Exam\\Exam_C\\新建 文本文档.txt");
            //ESM.ReplyTo=tbReplyTo.Text;//设定回复邮件地址.

            ESM.Priority = "high";//设定优先级，不过我实验着好像没啥用
            ESM.Html = true;//设定正文是否HTML格式。

            ESM.Subject = Subject;//设定邮件主题
            ESM.Body = Body;//设定邮件正文

            ESM.MailDomain = ReplyEMailDomain;//设定SMTP服务器地址
            //也可将将SMTP信息一次设置完成。写成
            //ESM.MailDomain="esmuser:esmpass@smtp.163.com:25";
            ESM.MailServerUserName = ReplyEMail;//设定SMTP验证的用户名
            ESM.MailServerPassWord = ReplyEMailPassword;//设定SMTP验证的密码
            //关于设定SMTP密码：如果在此处不设置的话，也可以在发送时使用在Send()函数的参数中设定。

            //发送Mail，我重载了3次Send函数，可满足不同喜好。
            //1.如果所有的属性都已经设置完毕，可直接使用无参数Send()
            //Send();

            //2.如果尚未设置SMTP服务信息也可使用如下形式设置
            //Send("esmuser:esmpass@smtp.163.com:25")
            //或者省略某些部分Send("esmuser:esmpass@smtp.163.com")或Send("smtp.163.com")

            //3.或者将全部信息都写在Send函数里，不过这样可读性太差了
            //Send(string smtpserver,string from,string fromname,string to,string toname,bool html,string subject,string body)


            //开始发送
            if (ESM.Send())
            {
                return String.Empty;
            }
            else
            {
                return ESM.ErrorMessage;
            }
            //Response.Write(ESM.Logs);

        }
        
    }
}
